//快麦打印函数
import { getCurrentUser } from '@/utils/authority';
import { message } from 'antd';

//执行打印
const handlePrint = (KMTEMPLATE, arr, cb) => {
  let index = 0;

  const printNext = () => {
    if (index < arr.length) {
      console.time('printNext');
      const data = {
        ...arr[index],
        callback: (res) => {
          console.timeEnd('printNext');
          console.log(res, `Printing ${index + 1} of ${arr.length}`);
          index++;
          requestAnimationFrame(printNext);
        }
      };
      KMTEMPLATE.printLabelNoPreview(data);
    } else {
      cb?.();
    }
  };

  printNext();
};


//打印唯一码
export const printKmUniqcode = (printData, printer, callback) => {
  //快麦通用参数
  const kmParams = {
    el: '#kuaimaiIframePrint',
    appId: '1666316938957',
    itemsId: '400',
    userId: getCurrentUser()?.id?.toString() ?? '',
  };
  // 初始化打印模板
  const KMTEMPLATE = new KM_Template();

  if (!KMTEMPLATE) {
    message.error('快麦打印程序加载未成功，请尝试刷新页面后重试');
    return;
  }

  // 处理打印数据
  const arr = printData.map(({ kmTemplateId, data }) => ({
    id: Number(kmTemplateId),
    usbList: [printer],
    data,
    ...kmParams,
  }));

  // 执行打印
  handlePrint(KMTEMPLATE, arr, callback);
}